import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:netflix_social/constants/app_constants.dart';
import 'package:netflix_social/models/video.dart';
import 'package:netflix_social/providers/video_provider.dart';
import 'package:netflix_social/providers/social_provider.dart';
import 'package:netflix_social/theme/app_theme.dart';
import 'package:netflix_social/widgets/content_row.dart';
import 'package:provider/provider.dart';

class VideoDetailScreen extends StatefulWidget {
  final String videoId;

  const VideoDetailScreen({
    Key? key,
    required this.videoId,
  }) : super(key: key);

  @override
  State<VideoDetailScreen> createState() => _VideoDetailScreenState();
}

class _VideoDetailScreenState extends State<VideoDetailScreen> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  bool _isDescriptionExpanded = false;
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    
    // 加载视频详情
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final videoProvider = Provider.of<VideoProvider>(context, listen: false);
      videoProvider.getVideoDetails(widget.videoId);
    });
  }
  
  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.backgroundColor,
      body: Consumer<VideoProvider>(
        builder: (context, videoProvider, child) {
          final video = videoProvider.currentVideo;
          
          if (videoProvider.isLoading || video == null) {
            return const Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(AppTheme.netflixRed),
              ),
            );
          }
          
          return CustomScrollView(
            slivers: [
              // 顶部图片和返回按钮
              _buildAppBar(context, video),
              
              // 视频信息
              SliverToBoxAdapter(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 标题和按钮组
                      _buildTitleSection(context, video),
                      
                      const SizedBox(height: 16),
                      
                      // 视频元数据（年份、分类、时长等）
                      _buildMetadataSection(context, video),
                      
                      const SizedBox(height: 16),
                      
                      // 操作按钮（播放、下载、分享）
                      _buildActionButtons(context, video),
                      
                      const SizedBox(height: 24),
                      
                      // 简介
                      _buildDescription(context, video),
                      
                      const SizedBox(height: 16),
                    ],
                  ),
                ),
              ),
              
              // 选项卡
              SliverPersistentHeader(
                delegate: _SliverAppBarDelegate(
                  TabBar(
                    controller: _tabController,
                    labelColor: Colors.white,
                    unselectedLabelColor: Colors.grey,
                    indicatorColor: AppTheme.netflixRed,
                    tabs: const [
                      Tab(text: '剧集'),
                      Tab(text: '相关推荐'),
                      Tab(text: '社区讨论'),
                    ],
                  ),
                ),
                pinned: true,
              ),
              
              // 选项卡内容
              SliverFillRemaining(
                child: TabBarView(
                  controller: _tabController,
                  children: [
                    // 剧集列表
                    _buildEpisodesTab(context, video),
                    
                    // 相关推荐
                    _buildRecommendationsTab(context, videoProvider),
                    
                    // 社区讨论
                    _buildCommentsTab(context, video),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildAppBar(BuildContext context, Video video) {
    return SliverAppBar(
      expandedHeight: 200,
      pinned: true,
      backgroundColor: AppTheme.backgroundColor,
      flexibleSpace: FlexibleSpaceBar(
        background: Stack(
          fit: StackFit.expand,
          children: [
            // 背景图片
            Image.network(
              video.thumbnailUrl,
              fit: BoxFit.cover,
            ),
            // 渐变遮罩
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.black.withOpacity(0.1),
                    Colors.black.withOpacity(0.5),
                    Colors.black.withOpacity(0.7),
                  ],
                ),
              ),
            ),
            // 播放按钮
            Center(
              child: IconButton(
                icon: const Icon(
                  Icons.play_circle_fill,
                  size: 60,
                  color: Colors.white,
                ),
                onPressed: () {
                  Navigator.pushNamed(
                    context,
                    AppConstants.playerRoute,
                    arguments: {
                      'videoId': video.id,
                      'isOffline': false,
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
      leading: IconButton(
        icon: Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.5),
            shape: BoxShape.circle,
          ),
          child: const Icon(Icons.arrow_back),
        ),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      actions: [
        IconButton(
          icon: Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.5),
              shape: BoxShape.circle,
            ),
            child: const Icon(Icons.favorite_border),
          ),
          onPressed: () {
            // 添加到收藏
            final videoProvider = Provider.of<VideoProvider>(context, listen: false);
            videoProvider.toggleFavorite(video.id);
          },
        ),
        IconButton(
          icon: Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.5),
              shape: BoxShape.circle,
            ),
            child: const Icon(Icons.share),
          ),
          onPressed: () {
            // 分享
            // 实际项目中，这里可能会调用分享功能
          },
        ),
      ],
    );
  }

  Widget _buildTitleSection(BuildContext context, Video video) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标题和评分
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                video.title,
                style: Theme.of(context).textTheme.headlineSmall,
              ),
              const SizedBox(height: 8),
              Row(
                children: [
                  RatingBar.builder(
                    initialRating: video.rating,
                    minRating: 1,
                    direction: Axis.horizontal,
                    allowHalfRating: true,
                    itemCount: 5,
                    itemSize: 18,
                    ignoreGestures: true,
                    itemBuilder: (context, _) => const Icon(
                      Icons.star,
                      color: Colors.amber,
                    ),
                    onRatingUpdate: (rating) {},
                  ),
                  const SizedBox(width: 8),
                  Text(
                    '${video.rating}',
                    style: TextStyle(
                      color: Colors.grey[400],
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
        // 点赞按钮
        Column(
          children: [
            IconButton(
              icon: const Icon(
                Icons.thumb_up_alt_outlined,
                color: Colors.white,
              ),
              onPressed: () {
                // 点赞
                // 实际项目中，这里可能会调用点赞功能
              },
            ),
            Text(
              '${video.likeCount}',
              style: TextStyle(
                color: Colors.grey[400],
                fontSize: 12,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildMetadataSection(BuildContext context, Video video) {
    return Wrap(
      spacing: 12,
      runSpacing: 8,
      children: [
        _buildMetadataItem(context, '${video.year}'),
        _buildMetadataItem(context, '${video.duration}分钟'),
        _buildMetadataItem(context, video.category),
        ...video.tags.map((tag) => _buildMetadataItem(context, tag)),
      ],
    );
  }

  Widget _buildMetadataItem(BuildContext context, String text) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.grey[800],
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        text,
        style: TextStyle(
          color: Colors.grey[300],
          fontSize: 12,
        ),
      ),
    );
  }

  Widget _buildActionButtons(BuildContext context, Video video) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        _buildActionButton(
          context,
          icon: Icons.play_arrow,
          label: '播放',
          isPrimary: true,
          onTap: () {
            Navigator.pushNamed(
              context,
              AppConstants.playerRoute,
              arguments: {
                'videoId': video.id,
                'isOffline': false,
              },
            );
          },
        ),
        _buildActionButton(
          context,
          icon: Icons.download,
          label: '下载',
          onTap: () {
            // 下载
            final videoProvider = Provider.of<VideoProvider>(context, listen: false);
            videoProvider.downloadVideo(video.id);
            
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('开始下载'),
                duration: Duration(seconds: 2),
              ),
            );
          },
        ),
        _buildActionButton(
          context,
          icon: Icons.share,
          label: '分享',
          onTap: () {
            // 分享
            // 实际项目中，这里可能会调用分享功能
          },
        ),
      ],
    );
  }

  Widget _buildActionButton(
    BuildContext context, {
    required IconData icon,
    required String label,
    bool isPrimary = false,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(
              color: isPrimary ? AppTheme.netflixRed : Colors.grey[800],
              shape: BoxShape.circle,
            ),
            child: Icon(
              icon,
              color: Colors.white,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            label,
            style: TextStyle(
              color: isPrimary ? Colors.white : Colors.grey[400],
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDescription(BuildContext context, Video video) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '简介',
          style: Theme.of(context).textTheme.titleMedium,
        ),
        const SizedBox(height: 8),
        Text(
          video.description,
          style: Theme.of(context).textTheme.bodyMedium?.copyWith(
            color: Colors.grey[400],
          ),
          maxLines: _isDescriptionExpanded ? null : 3,
          overflow: _isDescriptionExpanded ? null : TextOverflow.ellipsis,
        ),
        TextButton(
          onPressed: () {
            setState(() {
              _isDescriptionExpanded = !_isDescriptionExpanded;
            });
          },
          child: Text(
            _isDescriptionExpanded ? '收起' : '展开',
            style: const TextStyle(color: Colors.grey),
          ),
        ),
        const SizedBox(height: 8),
        if (video.director.isNotEmpty)
          _buildCrewInfo(context, '导演', video.director),
        if (video.cast.isNotEmpty)
          _buildCrewInfo(context, '演员', video.cast.join(', ')),
      ],
    );
  }

  Widget _buildCrewInfo(BuildContext context, String role, String names) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8.0),
      child: RichText(
        text: TextSpan(
          style: Theme.of(context).textTheme.bodyMedium,
          children: [
            TextSpan(
              text: '$role: ',
              style: TextStyle(
                color: Colors.grey[500],
                fontWeight: FontWeight.bold,
              ),
            ),
            TextSpan(
              text: names,
              style: TextStyle(
                color: Colors.grey[300],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildEpisodesTab(BuildContext context, Video video) {
    // 这里应该是剧集列表，但由于我们的模型中没有剧集信息，
    // 所以暂时只显示一个提示信息
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.movie,
            size: 64,
            color: Colors.grey[700],
          ),
          const SizedBox(height: 16),
          Text(
            '暂无剧集信息',
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
              color: Colors.grey[400],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRecommendationsTab(BuildContext context, VideoProvider videoProvider) {
    final recommendations = videoProvider.getSimilarVideos(videoProvider.currentVideo?.id ?? '');
    
    if (recommendations.isEmpty) {
      return Center(
        child: Text(
          '暂无推荐内容',
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
            color: Colors.grey[400],
          ),
        ),
      );
    }
    
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: recommendations.length,
      itemBuilder: (context, index) {
        final video = recommendations[index];
        return ListTile(
          contentPadding: EdgeInsets.zero,
          leading: Container(
            width: 120,
            height: 70,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              image: DecorationImage(
                image: NetworkImage(video.thumbnailUrl),
                fit: BoxFit.cover,
              ),
            ),
          ),
          title: Text(video.title),
          subtitle: Text(
            '${video.category} • ${video.year} • ${video.duration}分钟',
            style: TextStyle(
              color: Colors.grey[500],
              fontSize: 12,
            ),
          ),
          onTap: () {
            // 导航到视频详情页面
            Navigator.pushReplacementNamed(
              context,
              AppConstants.videoDetailRoute,
              arguments: video.id,
            );
          },
        );
      },
    );
  }

  Widget _buildCommentsTab(BuildContext context, Video video) {
    final socialProvider = Provider.of<SocialProvider>(context);
    final relatedPosts = socialProvider.getPostsByVideoId(video.id);
    
    if (relatedPosts.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.chat_bubble_outline,
              size: 64,
              color: Colors.grey[700],
            ),
            const SizedBox(height: 16),
            Text(
              '暂无讨论',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                color: Colors.grey[400],
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                // 创建讨论
                // 实际项目中，这里可能会导航到发布讨论的页面
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: AppTheme.netflixRed,
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 8,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20),
                ),
              ),
              child: const Text('发起讨论'),
            ),
          ],
        ),
      );
    }
    
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: relatedPosts.length,
      itemBuilder: (context, index) {
        final post = relatedPosts[index];
        return Card(
          color: AppTheme.cardColor,
          margin: const EdgeInsets.only(bottom: 16),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 作者信息
                Row(
                  children: [
                    CircleAvatar(
                      radius: 20,
                      backgroundImage: NetworkImage(post.author.avatar),
                    ),
                    const SizedBox(width: 12),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          post.author.username,
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Text(
                          '${post.createdAt.year}-${post.createdAt.month.toString().padLeft(2, '0')}-${post.createdAt.day.toString().padLeft(2, '0')}',
                          style: TextStyle(
                            color: Colors.grey[500],
                            fontSize: 12,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                // 内容
                Text(post.content),
                const SizedBox(height: 12),
                // 图片（如果有）
                if (post.images.isNotEmpty)
                  Container(
                    height: 150,
                    child: ListView.builder(
                      scrollDirection: Axis.horizontal,
                      itemCount: post.images.length,
                      itemBuilder: (context, imageIndex) {
                        return Container(
                          width: 150,
                          margin: const EdgeInsets.only(right: 8),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                            image: DecorationImage(
                              image: NetworkImage(post.images[imageIndex]),
                              fit: BoxFit.cover,
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                const SizedBox(height: 12),
                // 操作按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    _buildPostActionButton(
                      icon: Icons.favorite_border,
                      label: '${post.likeCount}',
                      onTap: () {
                        // 点赞
                        socialProvider.toggleLike(post.id);
                      },
                    ),
                    _buildPostActionButton(
                      icon: Icons.chat_bubble_outline,
                      label: '${post.commentCount}',
                      onTap: () {
                        // 评论
                        // 实际项目中，这里可能会显示评论输入框
                      },
                    ),
                    _buildPostActionButton(
                      icon: Icons.share,
                      label: '${post.shareCount}',
                      onTap: () {
                        // 分享
                        // 实际项目中，这里可能会调用分享功能
                      },
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildPostActionButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Row(
        children: [
          Icon(
            icon,
            size: 20,
            color: Colors.grey[400],
          ),
          const SizedBox(width: 4),
          Text(
            label,
            style: TextStyle(
              color: Colors.grey[400],
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar _tabBar;

  _SliverAppBarDelegate(this._tabBar);

  @override
  double get minExtent => _tabBar.preferredSize.height;

  @override
  double get maxExtent => _tabBar.preferredSize.height;

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: AppTheme.backgroundColor,
      child: _tabBar,
    );
  }

  @override
  bool shouldRebuild(covariant _SliverAppBarDelegate oldDelegate) {
    return false;
  }
}
